package com.example.mongodb;

import com.example.entity.Demo;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class DemoDaoImpl implements DemoDao {

    /**
     * 注入 MongoTemplate
     */
    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 保存
     *
     * @param demo 测试实体类
     */
    @Override
    public void save(Demo demo) {
        mongoTemplate.save(demo);
    }

    /**
     * 查询
     *
     * @param id 主键( 和Demo 实体类中@ID 注解标注的属性名一致 )
     */
    @Override
    public Demo findById(String id) {
        Query query = new Query(Criteria.where("demoId").is(id));
        Demo demo = mongoTemplate.findOne(query, Demo.class);
        return demo;
    }

    /**
     * 更新
     *
     * @param demo 测试实体类
     */
    @Override
    public void update(Demo demo) {
        Query query = new Query(Criteria.where("demoId").is(demo.getDemoId()));

        Update update = new Update();
        update.set("username", demo.getUsername());
        update.set("password", demo.getPassword());

        mongoTemplate.updateFirst(query, update, Demo.class);
    }

    /**
     * 删除
     *
     * @param id 主键
     */
    @Override
    public void removeById(String id) {
        Query query = new Query(Criteria.where("demoId").is(id));
        mongoTemplate.remove(query, Demo.class);
    }

}
